<?use pft\Prod\Product;
require_once('/var/www/html/new/com.inc.php');
//$a=ft::getFt();112013072200003
class Tpl{
	private $le;
	private $s;
	private $alllower="";
	private $memid=4;
	private static $link = null;
	private function __construct(){
		global $le;
		$this->le=$le;
		$this->s = SoapInit::GetsoapInside();
	}
	static function getLink(){
		if (null == self::$link){
			self::$link = new Tpl();
		}
		return self::$link;
	}
	function mylow($distid){
		$this->alllower="";
		if($distid[0]){
			$sel="select lvl,oid,sid from uu_distributor where id=".$distid[0];//echo $sel;
			$this->le->query($sel);
			$this->le->fetch_assoc();
			$lvl=$this->le->f("lvl");
			$oid=$this->le->f("oid");
			if(!$this->le->f("sid")){
				$lvl=0;
				$oid=0;
			}
		}
		else{
			return;
		}
		$sel="select id,sid from uu_distributor where status='1' and lvl<>2 and lvl>".(int)$lvl." and lvl<=14".($oid?" and oid=".$oid:"")." order by lvl ASC";//echo $sel;
		$this->le->query($sel);
		while($row=$this->le->fetch_assoc()){
			if(in_array($row['sid'],$distid)){$distid[]=$row['id'];}
		}
		$this->alllower=implode(",",$distid);
	}
	//isset:0获取插入所需的dprice,1更新所需相对op的差价,op为模板差价  函数皆为元单位
	function getNum($isset=0,$dptype=0,$dpercent=0,$sp=0,$fp=0,$up=0,$tp=0,$op=0){
		$sp=(float)$sp;
		if($isset){
			switch($dptype){
				case 0:
					$num=$dpercent-$op;
					break;
				case 1:
					$num=($fp+$sp)*$dpercent/100-$op;
					break;
				case 2:
					$num=$up+$dpercent-($fp+$sp)-$op;
					break;
				case 3:
					$num=$up*(1+$dpercent/100)-($fp+$sp)-$op;
					break;
				case 4:
					$num=$tp+$dpercent-($fp+$sp)-$op;
					break;
				case 5:
					$num=$tp*(1+$dpercent/100)-($fp+$sp)-$op;
					break;
			}
			$num=round($num);
			if($num+$sp+$op<$sp){return false;}
		}
		else{
			switch($dptype){
				case 0:
					$num=$sp+$dpercent;
					break;
				case 1:
					$num=($fp+$sp)*(1+$dpercent/100)-$fp;
					break;
				case 2:
					$num=$up+$dpercent-$fp;
					break;
				case 3:
					$num=$up*(1+$dpercent/100)-$fp;
					break;
				case 4:
					$num=$tp+$dpercent-$fp;
					break;
				case 5:
					$num=$tp*(1+$dpercent/100)-$fp;
					break;
			}
			$num=round($num);
			if($num<$sp){return false;}
		}
		return $num;
	}
	function rflex_id($pid=array()){
		if(!$pid)return array();
		$rid=array();
		$sel="select pid,pft_rflex_id from uu_jq_ticket where pid in (".implode(",",$pid).") and pft_rflex_id<>''";
		$this->le->query($sel);
		while($row=$this->le->fetch_assoc()){
			$rid[$row['pid']]=$row['pft_rflex_id'];
		}
		return $rid;
	}
	function upd($tplid,$_pri=array(),$stype=0){
		$ad_hoc=$all=$la=$temp=$has=$userid=$pid=$spri=$upri=$fpri=array();
		//获取原配置
		$sel="select * from uu_fx_pri_tpl where id=".$tplid." limit 1";
		$this->le->query($sel);
		$this->le->fetch_assoc();
		$distid=$this->le->f("distid");
	//	$dpercent=$this->le->f("dpercent");
	//	$dptype=$this->le->f("dptype");
	//	$rule=$this->le->f("rule")?explode("|",$this->le->f("rule")):array();
	//	$opri=$this->le->f("tid")?array_combine(explode("|",$this->le->f("tid")),explode("|",$this->le->f("price"))):array();
		//获取特配结算价和效验
		foreach($_pri as $k=>$v){
			$fp=$this->s->get_Dynamic_Price_Merge($k,date("Y-m-d"),2)/100;
			if($fp==-0.01){
				return "错误".$k."不可卖!";
			}
			$fpri[$k]=$fp;
			$p=$stype?$v:$v-$fp;
			if(filter_var($p, FILTER_VALIDATE_FLOAT)===false || $p<0){
				$sel="select p_name from uu_products where id=".$k." limit 1";
				$this->le->query($sel);
				$this->le->fetch_assoc();
				return $this->le->f("p_name")."设定的价格不正确";
			}
			$pid[]=$k;
			$pri[$k]=$p;
		}
		//获取使用者ID
		$sel="select fxid from uu_fx_tpl_cs where tplid=".$tplid;
		$this->le->query($sel);
		while($row=$this->le->fetch_assoc()){
			$userid[]=$row['fxid'];
		}
		if($userid){
			//获取已有
			$sel="select tid,pid from uu_priceset where aid=0 and status=0 and pid in (".implode(",",$userid).")";//echo $sel;
			$this->le->query($sel);
			while($row=$this->le->fetch_assoc()){
				$has[$row['tid']."-".$row['pid']]=$row;
			}
			//更新购买权限
			$upd="update pft_product_sale_list set pids='".implode(",",$pid)."' where fid in (".implode(",",$userid).") and aid=".$distid;
			$this->le->query($upd);
		
			foreach($pri as $k=>$v){
				foreach($userid as $uid){
					if(isset($has[$k."-".$uid])){continue;}
					$str.="(".($v*100).",".$k.",".$uid."),";
				}
				$upd="update uu_priceset set dprice=".($v*100)." where pid in (".implode(",",$userid).") and tid=".$k;
				$this->le->query($upd);
			}
			if($str){//插入
				$ins="insert into uu_priceset (dprice,tid,pid) values ".trim($str,",");//echo $ins."<br />";
				$this->le->query($ins);
			}
		}
		$tpl_t=implode("|",$pid);
		$tpl_p=implode("|",$pri);
		$upd="update uu_fx_pri_tpl set tid='".$tpl_t."',price='".$tpl_p."' where distid=".$distid." and id=".$tplid." limit 1";//echo $upd."<br />";
		if($this->le->query($upd)){
			return true;
		}
	}
	function add($did=0,$title,$_pri=array(),$stype=0,$perc=0,$dpt=0){
		$spri=$pri=array();
		$able=array_keys($_pri);
		//效验名称
		if($title){
			if(p_match($title)){
				return "模板名存在非法字符!";
			}
		}
		else{
			return "模板名为空!";
		}
		foreach($_pri as $k=>$v){
			if(!$stype){
				$fp=$this->s->get_Dynamic_Price_Merge($k,date("Y-m-d"),2)/100;
				if($fp==-0.01){
					return "错误".$k."不可卖!";
				}
			}
			$pri[$k]=$p=$stype?$v:$v-$fp-$spri[$k];
			if($p<0){
				$sel="select p_name from uu_products where id=".$k;
				$this->le->query($sel);
				$this->le->fetch_assoc();
				return $this->le->f("p_name")."设定的价格过低!";
			}
		}
		$ins="insert uu_fx_pri_tpl set title='".$title."',tid='".implode("|",array_keys($pri))."',price='".implode("|",$pri)."',distid=".$did;//echo $ins;
		if($this->le->query($ins)){
			return mysql_insert_id();
		}
	}
	function apply($did,$tplid){
		if(!$did){return "请指定分销商与模板";}
		if(!$tplid){
			$upd="delete from uu_fx_tpl_cs where fxid=".$did;
			$this->le->query($upd);
			return true;
		}
		$la=$temp=$spri=array();
		//已有设置
		$sel="select tid,dprice from uu_priceset where aid=0 and pid=".$did;
		$this->le->query($sel);
		while($row=$this->le->fetch_assoc()){
			$has[$row['tid']]=$row['dprice']/100;
		}
		//模板设置
		$sel="select tid,price,rule,dpercent,dptype,distid from uu_fx_pri_tpl where id=".$tplid." limit 1";
		$this->le->query($sel);
		$this->le->fetch_assoc();
		$distid=$this->le->f("distid");
		$able=$this->le->f("tid")?array_combine(explode("|",$this->le->f("tid")),explode("|",$this->le->f("price"))):array();
		
		$rid=$this->rflex_id(array_keys($able));
		//套用特价
		foreach($able as $k=>$v){
			if(isset($rid[$k]) && $did==$this->memid){
				if(!$pro){$pro = new Product($GLOBALS['le']);}
				$ret = json_decode($pro->SyncTicketState(1, $k),true);
				if($ret['status']!="ok"){
					return $k."|".$ret['msg'];
				}
				if(!$price){$price = new Price(-1);}
				$ret = $price->PriceSync($k, $rid[$k], ($v*100));
				if($ret!=100){
					return "票付通ID:".$k."关联ID".$rid[$k]."差价:".$v."失败:".$ret;
				}
			}
			$pids.=$k.",";
			if(isset($has[$k])){
				$temp[$k]=$v;
			}
			else{
				$str.="(".($v*100).",".$k.",".$did."),";
			}
		}
		//更新
		foreach($temp as $k=>$v){
			$upd="update uu_priceset set dprice=".($v*100)." where pid=".$did." and tid=".$k;//echo $upd;
			$this->le->query($upd);
		}
		//插入
		if($str){
			$ins="insert into uu_priceset (dprice,tid,pid) values ".trim($str,",");//echo $ins;
			$this->le->query($ins);
		}
		$sel="select pids from pft_product_sale_list where fid=".$did." and aid=".$distid." limit 1";
		$this->le->query($sel);
		$this->le->fetch_assoc();
		$diff=array_diff(explode(",",$this->le->f("pids")),explode(",",$pids));
		//删除
		$upd="update pft_product_sale_list set pids='".trim($pids,",")."' where fid=".$did." and aid=".$distid;//echo $del;
		$this->le->query($upd);
		if($diff){
			$pro = new Product($this->le);
			$sel="select pid,pft_rflex_id from uu_jq_ticket where pid in (".implode(",",$diff).")";
			$this->le->query($sel);
			while($row=$this->le->fetch_assoc()){
				$del[]=$row['pid'];
			}
			if($del){$ret = $pro->SyncTicketState(2, implode(",",$del));}
		}
		//去除特殊
		$upd="update uu_priceset set status=0 where pid=".$did;
		$this->le->query($upd);
		//模板套用设置
		$sel="select fxid from uu_fx_tpl_cs where fxid=".$did;
		$this->le->query($sel);
		$this->le->fetch_assoc();
		$str=$this->le->f("fxid")?"update uu_fx_tpl_cs set tplid=".$tplid." where fxid=".$did." limit 1":"insert uu_fx_tpl_cs set tplid=".$tplid.",fxid=".$did;
		$this->le->query($str);
		return true;
	}
	function rule($tplid,$perc,$dpt,$title="",$note=null){
		$temp=$la=$has=$userid=$diff=$spri=array();
		//效验名称
		if($note){
			if(p_match($note)){
				return "备注存在非法字符!";
			}
			if(strlen($note)>90){
				return "备注过长!";
			}
			$note=mb_convert_encoding($note, "UTF-8", "auto");
		}
		//效验名称
		if($title){
			if(p_match($title)){
				return "模板名存在非法字符!";
			}
			$title=mb_convert_encoding($title, "UTF-8", "auto");
		}
		//效验默认差价百分比
		if($perc){
			if(filter_var($perc, FILTER_VALIDATE_FLOAT)===false){
				return "默认差价存在非法字符!";
			}
		}
		elseif($perc!=0){
			return "需要默认差价!";
		}
		//默认差价
		if($dpt){
			if(filter_var($dpt, FILTER_VALIDATE_INT)===false){
				return "默认差价类型存在非法字符!";
			}
		}
		elseif($dpt!=0){
			return "需要默认差价类型!";
		}
		$sel="select fxid from uu_fx_tpl_cs where tplid=".$tplid;
		$this->le->query($sel);
		while($row=$this->le->fetch_assoc()){
			$userid[]=$row['fxid'];
		}
		if($userid){
			$sel="select rule,distid,dpercent,dptype from uu_fx_pri_tpl where id=".$tplid;//echo $sel;
			$this->le->query($sel);
			$this->le->fetch_assoc();
			$rule=$this->le->f("rule")?explode("|",$this->le->f("rule")):array();
			$dptype=$this->le->f("dptype");
			$dpercent=$this->le->f("dpercent");
			$distid=$this->le->f("distid");
			if($rule){
				if($distid){
					//上级配置
					$sel="select tid,dprice from uu_priceset s left join uu_products p on p.id=s.tid where aid=0 and p_status in (0,3,4) and num>0 and tid in (".implode(",",$rule).") and pid=".$distid;//echo $sel;
					$this->le->query($sel);
					while($row=$this->le->fetch_assoc()){
						$spri[$row['tid']]=$row['dprice']/100;
					}
				}
				//存在记录的下级
				if($userid){
					$sel="select tid,pid from uu_priceset where aid=0 and tid in (".implode(",",$rule).") and pid in (".implode(",",$userid).")";
					$this->le->query($sel);
					while($row=$this->le->fetch_assoc()){
						$has[]=$row['tid']."-".$row['pid'];
					}
				}
				foreach($rule as $v){
					if(!isset($spri[$v]) && $distid){continue;}
					$fp=$this->s->get_Dynamic_Price_Merge($v,date("Y-m-d"),2)/100;
					if($fp==-0.01){continue;}
					if($dpt==2 || $dpt==3 || $dptype==2 || $dptype==3){
						$up=$this->s->get_Dynamic_Price_Merge($v,date("Y-m-d"),2,"","",1)/100;
						if($up==-0.01){continue;}
					}
					if($dpt==4 || $dpt==5 || $dptype==4 || $dptype==5){
						$sel="select tprice from uu_jq_ticket where pid=".$v;
						$this->le->query($sel);
						$this->le->fetch_assoc();
						$tp=$this->le->f("tprice");
					}
					if(($num=$this->getNum(0,$dpt,$perc,$spri[$v],$fp,$up,$tp,0))===false){
						$sel="select p_name from uu_products where id=".$v;
						$this->le->query($sel);
						$this->le->fetch_assoc();
						return $this->le->f("p_name")."配置的价格低于结算价";
					}
					foreach($userid as $u){//补记录
						if(!in_array($v."-".$u,$has)){
							$str.="(".(($num)*100).",1,".$v.",".$u."),";
						}
					}
					$temp[$v]=$num-$this->getNum(0,$dptype,$dpercent,$spri[$v],$fp,$up,$tp,0);//记录更新差价
				}
				$this->mylow($userid);
				$alllower=$this->alllower;
				if($alllower && $temp){//更新
					//下级供应
					$sel="select id tid,apply_did pid from uu_products where apply_did in (".$alllower.") and p_status in (0,3,4,5) and apply_did<>".(int)$distid;//echo $sel;
					$this->le->query($sel);
					while($row=$this->le->fetch_assoc()){
						$la[]=$row;
					}
					//特殊无视
					$sel="select tid,pid from uu_priceset where aid=0 and status<>0 and pid in (".implode(",",$userid).")";
					$this->le->query($sel);
					while($row=$this->le->fetch_assoc()){
						$la[]=$row;
					}
					//获取供应
					foreach($la as $l){
						$this->mylow(array($l['pid']));
						$sel="select id from uu_priceset where aid=0 and pid in (".$this->alllower.") and tid=".$l['tid'];
						$this->le->query($sel);
						while($row=$this->le->fetch_assoc()){
							$noch[]=$row['id'];
						}
					}
					$noch=$noch?" and id not in (".implode(",",$noch).")":"";
					foreach($temp as $k=>$v){
						$upd="update uu_priceset set dprice=dprice+(".($v*100).") where pid in (".$alllower.") and tid=".$k.$noch;//echo $upd;
						$this->le->query($upd);
					}
				}
				//插入
				if($str){
					$ins="insert into uu_priceset (dprice,num,tid,pid) values ".trim($str,",");//echo $ins;
					$this->le->query($ins);
				}
			}
		}
		$upd="update uu_fx_pri_tpl set ".($title?"title='".$title."',":"")."dpercent=".$perc.",dptype=".$dpt.($note===null?"":",note='".$note."'")." where id=".$tplid;//echo $upd;
		if($this->le->query($upd)){return true;}
	}
	function del($tplid){
	/*	$sel="select d.id from uu_fx_tpl_cs c left join pft_member d on fxid=d.id where d.status=0 and tplid=".$tplid." limit 1";//echo $sel;
		$this->le->query($sel);
		$this->le->fetch_assoc();
		if($this->le->f("id")){
			return "要删除的模板尚有使用者";
		}*/
		$del="delete from uu_fx_tpl_cs where tplid=".$tplid;
		$this->le->query($del);
		$del="delete from uu_fx_pri_tpl where id = ".$tplid." limit 1";//echo $del;
		if($this->le->query($del)){return true;}
	}
	function excel($tplid){
		include('/var/www/html/new/jq/php_m/c/php-excel.class.php');
		$newArr=array();
		$newArr[0]['name']   	='产品名称';
		$newArr[0]['price']   	='价格（单位：元）';
		$sel="select * from uu_fx_pri_tpl where id=".$tplid;
		$this->le->query($sel);
		$this->le->fetch_assoc();
		$rule=$this->le->f("rule")?explode("|",$this->le->f("rule")):array();
		$able=$this->le->f("tid")?array_combine(explode("|",$this->le->f("tid")),explode("|",$this->le->f("price"))):array();
		$dptype=$this->le->f("dptype");
		$dpercent=$this->le->f("dpercent");
		$distid=$this->le->f("distid");
		$title=$this->le->f("title");
		//所有产品信息
		if($distid){
			$sel="select r.dprice,p_name,u.id,p_status from uu_priceset as r left join uu_products as u on u.id=r.tid where p_status in (0,3,4) and r.pid=".$distid." and u.id<>'' and r.aid=0 and contact_id<>0 and num>0 order by contact_id,u.id";
			$this->le->query($sel);
			while($row=$this->le->fetch_assoc()){
				if($row['p_status']==4)$only[]=$row['id'];
				$prod[$row['id']]=$row;
			}
		}
		else{
			$sel="select p_name,id from uu_products where p_status in (0,3) and contact_id<>0 order by contact_id,id";
			$this->le->query($sel);
			while($row=$this->le->fetch_assoc()){
				$prod[$row['id']]=$row;
			}
		}
		if($only){//去除非本机构的仅下级产品
			$sel="select p.id,oid from uu_products p left join uu_distributor d on p.apply_did=d.id where p.id in (".implode(",",$only).")";
			$this->le->query($sel);
			while($row=$this->le->fetch_assoc()){
				if($row['oid']!=$oid){
					unset($prod[$row['id']]);
				}
			}
		}
		//获取价格
		foreach($prod as $k=>$v){
			$fp=$this->s->get_Dynamic_Price_Merge($k,date("Y-m-d"),2);
			if($fp!=-1){
				$fpri[$k]=$fp/100;
				if($did)$spri[$k]=($fp+$prod[$k]['dprice'])/100;
			}
			else{
				unset($prod[$k]);
			}
			if($dptype==2 || $dptype==3){
				$up=$this->s->get_Dynamic_Price_Merge($k,date("Y-m-d"),2,"","",1);
				if($up!=-1){$upri[$k]=$up/100;}
				else{
					unset($prod[$k]);
				}
			}
			if($dptype==4 || $dptype==5){
				$sel="select tprice from uu_jq_ticket where pid=".$v;
				$this->le->query($sel);
				$this->le->fetch_assoc();
				$tpri[$k]=$this->le->f("tprice");
			}
		}
		$i=1;
		foreach($rule as $v){
			if(!isset($prod[$v])){continue;}
			$newArr[$i]['name']=$prod[$v]['p_name'];
			$newArr[$i]['price']=$fpri[$v]+$this->getNum(0,$dptype,$dpercent,$spri[$v],$fpri[$v],$upri[$v],$tpri[$v]);
			$i++;
		}
		foreach($able as $k=>$v){
			if(!isset($prod[$k])){continue;}
			$newArr[$i]['name']=$prod[$k]['p_name'];
			$newArr[$i]['price']=$fpri[$k]+$spri[$k]+$v;
			$i++;
		}
		$xls = new Excel_XML('UTF-8', true, $title);
		$xls->addArray($newArr);
		$date=date('Ymd').$title.'价格模板';
		$xls->generateXML($date);
	}
	function unusual($did,$pri=array(),$stype=0){
		$sid=0;
		$_pid=array_keys($pri);
		$lvl=$pid=$sec=$temp=$has=$fpri=array();
		if($_pid){
			foreach($_pid as $v){
				$_v=explode(",",$v);
				$fp=$this->s->get_Dynamic_Price_Merge($_v[0],date("Y-m-d"),2);
				if($fp!=-1){
					$fpri[$_v[0]]=$fp/100;
					if(isset($_v[1])){
						$sec[]=$_v[0];
						if(!$sid){
							$sid=$_v[1];
						}
					}
					else{
						$pid[]=$_v[0];
					}
				}
			}
			if($sec){
				$sel="select s.tid,dprice,lvl,sid from pft_p_apply_evolute e left join uu_priceset s on s.tid=e.pid and s.aid=e.sid and e.pid=fid where fid=".$sid." and active=1 and e.pid in (".implode(",",$sec).")";
				$this->le->query($sel);
				while($row=$this->le->fetch_assoc()){
					$fpri[$row['tid']]+=$row['dprice']/100;
					if($row['lvl']==2){$lvl[$row['tid']]=$row['sid'];}
				}
				foreach($lvl as $k=>$v){
					$sel.="(tid=".$k." and pid=".$v." and aid=0) or ";
				}
				if($sel){
					$sel="select dprice,tid from uu_priceset where ".trim($sel,"or");
					$this->le->query($sel);
					while($row=$this->le->fetch_assoc()){
						$fpri[$row['tid']]+=$row['dprice']/100;
					}
				}
			}
			$sel="select tid,dprice from uu_priceset where (aid=0 or aid=".$sid.") and tid in (".implode(",",$pid).") and pid=".$did." order aid ASC";
			$this->le->query($sel);
			while($row=$this->le->fetch_assoc()){
				$has[$row['tid']]=$row['dprice']/100;
			}
			foreach($pri as $k=>$val){
				$_v=explode(",",$val);
				if(!isset($fpri[$k])){continue;}
				$p=$stype?(float)$v:(float)$v-$fpri[$k];
				if($p<0){
					$sel="select p_name from uu_products where id=".$k;
					$this->le->query($sel);
					$this->le->fetch_assoc();
					return $this->le->f("p_name")."配置的价格过低";
				}
				if(isset($has[$k])){
					$temp[$k]=$p-$has[$k];
				}
				else{
					$str.="(".($p*100).",".$k.",".$did.",1),";
				}
			}
			if($did==$this->memid){
				$rid=$this->rflex_id($pid);
				foreach($pri as $k=>$v){
					if(isset($rid[$k])){
						if(!$pro){$pro = new Product($GLOBALS['le']);}
						$ret = json_decode($pro->SyncTicketState(1, $k),true);
						if($ret['status']!="ok"){
							return $k.$ret['msg'];
						}
						if(!$price){$price = new Price(-1);}
						$d=$stype?(float)$v:(float)$v-$fpri[$k];
						$ret = $price->PriceSync($k, $rid[$k], ($d*100));
						if($ret!=100){
							return $k."-".$rid[$k]."-".$d."失败".$ret;
						}
					}
				}
			}
			foreach($temp as $k=>$v){
				$upd="update uu_priceset set dprice=dprice+(".($v*100).") where pid=".$did." and tid=".$k;//echo $upd;
				$this->le->query($upd);
			}
			if($str){
				$ins="insert into uu_priceset (dprice,tid,pid,status) values ".trim($str,",");//echo $ins;
				$this->le->query($ins);
			}
			$upd="update uu_priceset set status=1 where pid=".$did." and tid in (".implode(",",$pid).")";
			$this->le->query($upd);
		}
		return true;
	}
	function getTpl($tplid){
		$sel="select * from uu_fx_pri_tpl where id=".$tplid." limit 1";
		$this->le->query($sel);
		return $this->le->fetch_assoc();
	}
}?>